package com.demo.search.xml;

import java.io.File;
import java.io.IOException;
import java.util.Enumeration;
import java.util.Properties;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.TransformerException;

import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.document.Field.TermVector;
import org.apache.lucene.index.CorruptIndexException;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriterConfig;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.search.TopDocs;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;
import org.apache.lucene.store.LockObtainFailedException;
import org.apache.lucene.store.RAMDirectory;
import org.apache.lucene.util.Version;
import org.apache.lucene.xmlparser.CorePlusExtensionsParser;
import org.apache.lucene.xmlparser.QueryTemplateManager;
import org.xml.sax.SAXException;

/**
 * 检索服务
 * @author ryuu.kk
 *
 */
public class SearchServlet extends HttpServlet {

	/**
	 * 版本序列化ID
	 */
	private static final long serialVersionUID = 1423273514240633589L;

	private IndexSearcher searcher;
	private QueryTemplateManager queryTemplateManager;
	private CorePlusExtensionsParser xmlParser;
	private Analyzer analyzer = new StandardAnalyzer(Version.LUCENE_36);
	
	public void init(ServletConfig config) throws ServletException {
		super.init(config);
		
		try {
			openExampleIndex();
			queryTemplateManager = new QueryTemplateManager(getServletContext().getResourceAsStream("/WEB-INF/JobSearch.xsl"));
			xmlParser = new CorePlusExtensionsParser("contents", analyzer);
			//XmlQueryParser
		} catch (Exception e) {
			e.printStackTrace();
		} 
		
	}
	
	@SuppressWarnings("unchecked")
	public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		Properties comptedFprmFidlds = new Properties();
		Enumeration<String> pNames = request.getParameterNames();
		while(pNames.hasMoreElements()) {
			String propName = pNames.nextElement();
			String value = request.getParameter(propName);
			if (value != null && (value.trim().length() > 0)) {
				comptedFprmFidlds.setProperty(propName, value);
			}
		}
		
		try {
			org.w3c.dom.Document xmlQuery = queryTemplateManager.getQueryAsDOM(comptedFprmFidlds);
			Query query = xmlParser.getQuery(xmlQuery.getDocumentElement());
			
			TopDocs topDocs = searcher.search(query, 10);
			
			if (topDocs != null) {
				ScoreDoc[] sd = topDocs.scoreDocs;
				Document[] results = new Document[sd.length];
				for (int i = 0; i < results.length; i++) {
					results[i] = searcher.doc(sd[i].doc);
				}
				request.setAttribute("results", results);
			}
			RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/index.jsp");
			dispatcher.forward(request, response);
		} catch (Exception e) {
			e.printStackTrace();
		} 
	}
	
	public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/search.jsp");
		dispatcher.forward(request, response);
	}

	
	private void openExampleIndex() throws CorruptIndexException, LockObtainFailedException, IOException {
		//RAMDirectory directory = new RAMDirectory();
		Directory directory = FSDirectory.open(new File("C:\\development\\lucence\\index"));
		//IndexWriterConfig writerConfig = new IndexWriterConfig(Version.LUCENE_36, new StandardAnalyzer(Version.LUCENE_36));
		Analyzer analyzer = new StandardAnalyzer(Version.LUCENE_36);
		IndexWriterConfig writerConfig = new IndexWriterConfig(Version.LUCENE_36, analyzer);
		IndexWriter writer = new IndexWriter(directory, writerConfig);
		// 建立索引
		Document doc = new Document();
		doc.add(new Field("contents", "the cool cat jump over the lazy dog. Java编程语言   计算机", Field.Store.YES, Field.Index.ANALYZED, TermVector.WITH_POSITIONS_OFFSETS));
		writer.addDocument(doc);
		writer.close();
		
		//
		IndexReader indexReader = IndexReader.open(directory);
		
		// 索引快照
		IndexReader newReader = IndexReader.openIfChanged(indexReader);
		if (newReader != null) {
			indexReader.close();
			indexReader = newReader;
		}
		searcher = new IndexSearcher(indexReader);
	}
}
